package com.haima.sage.bigdata.api.frame;

import java.io.IOException;

import com.haima.sage.bigdata.api.common.EsUtils;
import com.haima.sage.bigdata.api.entity.api.data.cases.ConfigType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.haima.sage.bigdata.api.common.DbUtils;
import com.haima.sage.bigdata.api.dao.StorageRepository;
import com.haima.sage.bigdata.api.entity.storage.Storage;

@Component
public class StorageApplicationRunner implements ApplicationRunner {
    private static final Logger LOG = LogManager.getLogger(StorageApplicationRunner.class);

    private final StorageRepository dao;

    @Autowired
    public StorageApplicationRunner(StorageRepository dao) {
        this.dao = dao;
    }

    @Override
    public void run(ApplicationArguments args) {
        LOG.info("api service is running ...");
        Iterable<Storage> storages = dao.findAll();
        for (Storage storage : storages) {
            try {
                ConfigType type = ConfigType.DB;
                if (storage.getType() != null) {
                    type = storage.getType();
                }
                switch (type) {
                    case ES:
                        EsUtils.merge(storage);
                        break;
                    default:
                        DbUtils.merge(storage);
                }
            } catch (Exception e) {
                LOG.error("create connection pool error:" + storage.getData(), e);
            }
        }
    }
}
